<template>
  <el-container class="ai-layout">
    <!-- 左侧：对话列表 -->
    <ConversationList
      :active-id="activeConversationId"
      ref="conversationListRef"
      @on-conversation-create="handleConversationCreateSuccess"
      @on-conversation-click="handleConversationClick"
      @on-conversation-clear="handleConversationClear"
      @on-conversation-delete="handlerConversationDelete"
    />
    <!-- 右侧：对话详情 -->
    <el-container class="detail-container">
      <el-header class="header">
        <div class="title">
          {{ activeConversation?.title ? activeConversation?.title : "对话" }}
          <span v-if="activeMessageList.length">({{ activeMessageList.length }})</span>
        </div>
        <div class="btns" v-if="activeConversation">
          <el-button type="primary" bg plain size="big" class="btn" :icon="Setting" @click="openChatConversationUpdateForm">
            <span v-html="activeConversation?.modelName"></span>
          </el-button>
          <el-button size="big" class="btn" :icon="Delete" @click="handlerMessageClear" />
          <el-button size="big" class="btn" :icon="Download" />
          <el-button size="big" class="btn" :icon="Top" @click="handleGoTopMessage" />
        </div>
      </el-header>
      <!-- main：消息列表 -->
      <el-main class="main-container">
        <div>
          <div class="message-container">
            <!-- 情况一：消息加载中 -->
            <MessageLoading v-if="activeMessageListLoading" />
            <!-- 情况二：无聊天对话时 -->
            <MessageNewConversation v-if="!activeConversation" @on-new-conversation="handleConversationCreate" />
            <!-- 情况三：消息列表为空 -->
            <MessageListEmpty
              v-if="!activeMessageListLoading && messageList.length === 0 && activeConversation"
              @on-prompt="doSendMessage"
            />
            <!-- 情况四：消息列表不为空 -->
            <MessageList
              v-if="!activeMessageListLoading && messageList.length > 0"
              ref="messageRef"
              :conversation="activeConversation"
              :list="messageList"
              @on-delete-success="handleMessageDelete"
              @on-edit="handleMessageEdit"
              @on-refresh="handleMessageRefresh"
            />
          </div>
        </div>
      </el-main>

      <!-- 底部 -->
      <el-footer class="footer-container">
        <form class="prompt-from">
          <textarea
            class="prompt-input"
            v-model="prompt"
            @keydown="handleSendByKeydown"
            @input="handlePromptInput"
            @compositionstart="onCompositionstart"
            @compositionend="onCompositionend"
            placeholder="问我任何问题...（Shift+Enter 换行，按下 Enter 发送）"
          ></textarea>
          <div class="prompt-btns">
            <div>
              <el-switch v-model="enableContext" />
              <span class="ml-5px text-14px text-#8f8f8f">上下文</span>
            </div>
            <el-button
              type="primary"
              size="default"
              @click="handleSendByButton"
              :loading="conversationInProgress"
              v-if="conversationInProgress == false"
            >
              {{ conversationInProgress ? "进行中" : "发送" }}
            </el-button>
            <el-button type="danger" size="default" @click="stopStream()" v-if="conversationInProgress == true"> 停止 </el-button>
          </div>
        </form>
      </el-footer>
    </el-container>
  </el-container>
  <!-- 更新对话 Form -->
  <ConversationUpdateForm ref="conversationUpdateFormRef" @success="handleConversationUpdateSuccess" />
</template>

<script setup lang="ts">
import MessageList from "./components/message/MessageList.vue";
import MessageListEmpty from "./components/message/MessageListEmpty.vue";
import MessageLoading from "./components/message/MessageLoading.vue";
import { ElMessage } from "element-plus";
import MessageNewConversation from "./components/message/MessageNewConversation.vue";
import { ref, defineOptions, computed, nextTick } from "vue";
import ConversationList from "@/views/ai/chat/components/conversation/ConversationList.vue";
import ConversationUpdateForm from "@/views/ai/chat/components/conversation/ConversationUpdateForm.vue";
import { useMessage } from "@/hooks/useMessage";
import { Chat } from "@/api/ai/chat";
import { getListByChatId, ChatMessage } from "@/api/ai/chatmessage";
import { Setting, Download, Top, Delete } from "@element-plus/icons-vue";

defineOptions({ name: "AiChat" });

const message = useMessage();
const activeConversationId = ref<number | null>(null); // 选中的对话编号

const activeMessageListLoading = ref<Boolean>(false); // activeMessageList 是否正在加载中

const activeConversation = ref<Chat.ResChat>(); // 选中的 Conversation

const activeMessageList = ref<ChatMessage.ResChatMessage[]>([]); // 选中对话的消息列表
const conversationInProgress = ref<Boolean>(false);
const prompt = ref<string>(); // prompt (提示)
const isComposing = ref(false); // 判断用户是否在输入
// 聊天对话
const conversationListRef = ref<InstanceType<typeof ConversationList> | null>();
// 是否开启上下文
const enableContext = ref<Boolean>(false);
const activeMessageListLoadingTimer = ref<any>(); // activeMessageListLoading Timer 定时器。如果加载速度很快，就不进入加载中
const conversationInAbortController = ref<any>(); // 对话进行中 abort 控制器(控制 stream 对话)
// 接收 Stream 消息
const receiveMessageFullText = ref<string>("");
const receiveMessageDisplayedText = ref<string>("");
// 消息滚动
const textSpeed = ref<number>(50); // 打字速度（以毫秒计）
const textRoleRunning = ref<boolean>(false);
const inputTimeout = ref<any>(); // 处理输入中回车的定时器
const messageRef = ref();

const onCompositionend = () => {
  console.log("onCompositionend");
};
const onCompositionstart = () => {
  console.log("onCompositionstart");
};
/** 处理 prompt 输入变化 */
const handlePromptInput = event => {
  // 非输入法 输入设置为 true
  if (!isComposing.value) {
    // 回车 event data 是 null
    if (event.data == null) {
      return;
    }
    isComposing.value = true;
  }
  // 清理定时器
  if (inputTimeout.value) {
    clearTimeout(inputTimeout.value);
  }
  // 重置定时器
  inputTimeout.value = setTimeout(() => {
    isComposing.value = false;
  }, 400);
};
/** 处理聊天对话的创建成功 */
const handleConversationCreateSuccess = () => {
  // 创建新的对话，清空输入框
  prompt.value = "";
};
/**
 * 点击某个对话
 *
 * @param conversation 选中的对话
 * @return 是否切换成功
 */
const handleConversationClick = async (chat: Chat.ResChat) => {
  // 对话进行中，不允许切换
  if (conversationInProgress.value) {
    message.alert("对话中，不允许切换!");
    return false;
  }

  // 更新选中的对话 id
  activeConversationId.value = chat.id;
  activeConversation.value = chat;
  // 刷新 message 列表
  await getMessageList();
  // 滚动底部
  scrollToBottom(true);
  // 清空输入框
  prompt.value = "";
  return true;
};
/** 清空选中的对话 */
const handleConversationClear = async () => {
  // 对话进行中，不允许切换
  // 对话进行中，不允许切换
  if (conversationInProgress.value) {
    message.alert("对话中，不允许切换!");
    return false;
  }
  activeConversationId.value = null;
  activeConversation.value = {} as Chat.ResChat;
  activeMessageList.value = [];
};

/** 删除某个对话*/
const handlerConversationDelete = async (delChat: Chat.ResChat) => {
  // 删除的对话如果是当前选中的，那么就重置
  if (activeConversationId.value === delChat.id) {
    await handleConversationClear();
  }
};

/**
 * 消息列表
 *
 * 和 {@link #getMessageList()} 的差异是，把 systemMessage 考虑进去
 */
const messageList = computed(() => {
  if (activeMessageList.value.length > 0) {
    return activeMessageList.value;
  }
  // 没有消息时，如果有 systemMessage 则展示它
  if (activeConversation.value?.systemMessage) {
    return [
      {
        id: 0,
        type: "system",
        content: activeConversation.value.systemMessage
      }
    ];
  }
  return [];
});
/** 停止 stream 流式调用 */
const stopStream = () => {
  // tip：如果 stream 进行中的 message，就需要调用 controller 结束
  if (conversationInAbortController.value) {
    conversationInAbortController.value.abort();
  }
  // 设置为 false
  conversationInProgress.value = false;
};
/** 处理来自【发送】按钮的发送消息 */
const handleSendByButton = () => {
  doSendMessage(prompt.value?.trim() as string);
};
/** 修改聊天对话 */
const openChatConversationUpdateForm = async () => {
  console.log("openChatConversationUpdateForm");
};
/**
 * 处理消息清空
 */
const handlerMessageClear = () => {
  console.log("handlerMessageClear");
};
/**
 * 消息回到顶部
 */
const handleGoTopMessage = () => {
  console.log("handleGoTopMessage");
};
/**
 * 处理聊天对话的创建成功
 */
const handleConversationCreate = async () => {
  // 创建对话
  await conversationListRef.value?.createChat();
};
/** 真正执行【发送】消息操作 */
const doSendMessage = async (content: string) => {
  // 校验
  if (content.length < 1) {
    ElMessage.error("内容为空！");
    return;
  }
  if (activeConversationId.value == null) {
    ElMessage.error("还没创建对话!!");
    return;
  }
  // 清空输入框
  prompt.value = "";
  // 执行发送
  await doSendMessageStream({
    chatId: activeConversationId.value,
    content: content
  } as ChatMessage.ResChatMessage);
};
/**
 * 真正执行【发送】消息操作
 */
const doSendMessageStream = async (chatMessage: ChatMessage.ResChatMessage) => {
  // 创建 AbortController 实例，以便中止请求
  conversationInAbortController.value = new AbortController();
  // 标记对话进行中
  conversationInProgress.value = true;
  // 设置为空
  receiveMessageFullText.value = "";
  try {
    // 1.1 先添加两个假数据，等 stream 返回再替换
    activeMessageList.value.push({
      id: -1,
      chatId: activeConversationId.value,
      type: "user",
      content: chatMessage.content,
      createTime: new Date()
    } as ChatMessage.ResChatMessage);
    activeMessageList.value.push({
      id: -2,
      chatId: activeConversationId.value,
      type: "assistant",
      content: "思考中...",
      createTime: new Date()
    } as ChatMessage.ResChatMessage);
    // 1.2 滚动到最下面
    await nextTick();
    await scrollToBottom(); // 底部
    // 1.3 开始滚动
    await textRoll();

    // 2. 发送 event stream
    let isFirstChunk = true; // 是否是第一个 chunk 消息段
    // 首次返回需要添加一个 message 到页面，后面的都是更新
    if (isFirstChunk) {
      isFirstChunk = false;
      // 弹出两个假数据
      activeMessageList.value.pop();
      activeMessageList.value.pop();
      // 更新返回的数据
    }

    // 滚动到最下面
    await scrollToBottom();
  } catch {}
};

const textRoll = async () => {
  let index = 0;
  try {
    // 只能执行一次
    if (textRoleRunning.value) {
      return;
    }
    // 设置状态
    textRoleRunning.value = true;
    receiveMessageDisplayedText.value = "";
    const task = async () => {
      // 调整速度
      const diff = (receiveMessageFullText.value.length - receiveMessageDisplayedText.value.length) / 10;
      if (diff > 5) {
        textSpeed.value = 10;
      } else if (diff > 2) {
        textSpeed.value = 30;
      } else if (diff > 1.5) {
        textSpeed.value = 50;
      } else {
        textSpeed.value = 100;
      }
      // 对话结束，就按 30 的速度
      if (!conversationInProgress.value) {
        textSpeed.value = 10;
      }

      if (index < receiveMessageFullText.value.length) {
        receiveMessageDisplayedText.value += receiveMessageFullText.value[index];
        index++;

        // 更新 message
        const lastMessage = activeMessageList.value[activeMessageList.value.length - 1];
        lastMessage.content = receiveMessageDisplayedText.value;
        // 滚动到住下面
        await scrollToBottom();
        // 重新设置任务
        timer = setTimeout(task, textSpeed.value);
      } else {
        // 不是对话中可以结束
        if (!conversationInProgress.value) {
          textRoleRunning.value = false;
          clearTimeout(timer);
        } else {
          // 重新设置任务
          timer = setTimeout(task, textSpeed.value);
        }
      }
    };
    let timer = setTimeout(task, textSpeed.value);
  } catch {}
};

const handleMessageDelete = () => {
  console.log("handleMessageDelete");
};

const handleMessageEdit = () => {
  console.log("handleMessageEdit");
};

const handleMessageRefresh = () => {
  console.log("handleMessageRefresh");
};
/**
 * 对话更新成功，刷新最新信息
 */
const handleConversationUpdateSuccess = async () => {
  // 对话更新成功，刷新最新信息
  console.log("对话更新");
};
/** 处理来自 keydown 的发送消息 */
const handleSendByKeydown = async (event: any) => {
  // 判断用户是否在输入
  if (isComposing.value) {
    return;
  }
  // 进行中不允许发送
  if (conversationInProgress.value) {
    return;
  }
  const content = prompt.value?.trim() as string;
  if (event.key === "Enter") {
    if (event.shiftKey) {
      // 插入换行
      prompt.value += "\r\n";
      event.preventDefault(); // 防止默认的换行行为
    } else {
      // 发送消息
      await doSendMessage(content);
      event.preventDefault(); // 防止默认的提交行为
    }
  }
};
/** 滚动到 message 底部 */
const scrollToBottom = async (isIgnore?: boolean) => {
  await nextTick();
  if (messageRef.value) {
    messageRef.value.scrollToBottom(isIgnore);
  }
};
/**
 * 获取消息列表
 */
const getMessageList = async () => {
  try {
    if (activeConversationId.value === null) {
      return;
    }
    // Timer 定时器，如果加载速度很快，就不进入加载中
    activeMessageListLoadingTimer.value = setTimeout(() => {
      activeMessageListLoading.value = true;
    }, 60);

    // 获取消息列表
    const res = await getListByChatId(activeConversationId.value);
    activeMessageList.value = res.data;
    // 滚动到最下面
    await nextTick();
    await scrollToBottom();
  } finally {
    // time 定时器，如果加载速度很快，就不进入加载中
    if (activeMessageListLoadingTimer.value) {
      clearTimeout(activeMessageListLoadingTimer.value);
    }
    // 加载结束
    activeMessageListLoading.value = false;
  }
};
</script>

<style lang="scss" scoped>
.ai-layout {
  flex: 1;
  width: 100%;
  height: 100%;
  color: var(--el-header-text-color);
  background: var(--el-header-bg-color);
}
.conversation-container {
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 10px 10px 0;
  .btn-new-conversation {
    padding: 18px 0;
  }
  .search-input {
    margin-top: 20px;
  }
  .conversation-list {
    margin-top: 20px;
    .conversation {
      display: flex;
      flex: 1;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      padding: 0 5px;
      margin-top: 10px;
      line-height: 30px;
      cursor: pointer;
      border-radius: 5px;
      &.active {
        background-color: #931616;
        .button {
          display: inline-block;
        }
      }
      .title-wrapper {
        display: flex;
        flex-direction: row;
        align-items: center;
      }
      .title {
        max-width: 220px;
        padding: 5px 10px;
        overflow: hidden;
        font-size: 14px;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .avatar {
        display: flex;
        flex-direction: row;
        justify-items: center;
        width: 28px;
        height: 28px;
      }

      // 对话编辑、删除
      .button-wrapper {
        right: 2px;
        display: flex;
        flex-direction: row;
        justify-items: center;
        color: #606266;
        .el-icon {
          margin-right: 5px;
        }
      }
    }
  }

  // 角色仓库、清空未设置对话
  .tool-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    line-height: 35px;
    color: var(--el-text-color);
    > div {
      display: flex;
      align-items: center;
      padding: 0;
      margin: 0;
      color: #606266;
      cursor: pointer;
      > span {
        margin-left: 5px;
      }
    }
  }
}

// 头部
.detail-container {
  .header {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0 0 0 0 #dcdfe6;
    .title {
      font-size: 18px;
      font-weight: bold;
    }
    .btns {
      display: flex;
      flex-direction: row;
      justify-content: flex-end;
      width: 300px;

      //justify-content: space-between;
      .btn {
        padding: 10px;
        font-size: 20px;
      }
    }
  }
}

// main 容器
.main-container {
  position: relative;
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
  .message-container {
    position: absolute;
    inset: 0;
    padding: 0;
    margin: 0;
    overflow-y: hidden;
  }
}

// 底部
.footer-container {
  display: flex;
  flex-direction: column;
  height: auto;
  padding: 0;
  margin: 0;
  .prompt-from {
    display: flex;
    flex-direction: column;
    height: auto;
    padding: 9px 10px;
    margin: 10px 20px 20px;
    border: 1px solid #e3e3e3;
    border-radius: 10px;
  }
  .prompt-input {
    box-sizing: border-box;
    font-size: 15px;
    height: 80px;
    padding: 0 2px;
    overflow: auto;
    resize: none;

    //box-shadow: none;
    border: none;
  }
  .prompt-input:focus {
    outline: none;
  }
  .prompt-btns {
    display: flex;
    justify-content: space-between;
    padding-top: 5px;
    padding-bottom: 0;
  }
}
</style>
